﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace OpenST
{
    class KeyboardInput
    {
        public class KeyEventHandle
        {
            public Keys key;
            public bool LastPressed;
            public event KeyPressEvent OnPress;

            public void TrySendEvent()
            {
                if (OnPress != null)
                {
                    OnPress();
                }
            }
        }
        public delegate void KeyPressEvent();

        private List<KeyEventHandle> EventDict;

        public void AddKeyEvent(Keys key, KeyPressEvent Handler)
        {
            bool KeyExists = false;

            int i = 0;
            foreach (KeyEventHandle khand in EventDict)
            {
                if (khand.key == key)
                {
                    KeyExists = true;
                }
                else
                {
                    i++;
                }
            }

            if (KeyExists == false)
            {
                KeyEventHandle keyhandler = new KeyEventHandle();
                keyhandler.key = key;
                keyhandler.OnPress += Handler;

                EventDict.Add(keyhandler);
            }
            else
            {
                EventDict[i].OnPress += Handler;
            }

            //int x;
        }

        Game game;

        public KeyboardInput(Game thegame)
        {

            game = thegame;
            EventDict = new List<KeyEventHandle>();
        }

        public void Update()
        {
            KeyboardState keyboardstate = Keyboard.GetState();

            for (int k = 0; k < EventDict.Count; k++)
            {
                // Is the key pressed?
                if (keyboardstate.IsKeyDown(EventDict[k].key))
                {
                    // Was it pressed before?
                    if (EventDict[k].LastPressed == false)
                    {
                        // No? Then send the event and mark is as pressed...
                        // But only if an event was set...
                        EventDict[k].TrySendEvent();
                        EventDict[k].LastPressed = true;
                    } 
                }
                else
                {
                    EventDict[k].LastPressed = false;
                }


            }
        }
    }
}
